package com.teach.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//@WebServlet("/demo02.let")
@WebServlet({
	"/demo02.let",
	"/demo02/*",
	"*.demo02"
})
public class Demo01Servlet extends HttpServlet {
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");//设置请求[正文]的字符集编码
//		request.getInputStream();//获取请求[正文]的输入流
//		request.getReader();//获取请求[正文]的读取流
//		request.getParameter("name");//根据请求参数名，获取请求参数值
		//上面三个方法互斥
		String method = request.getMethod();//获取请求方式：get/post
		String name = request.getParameter("name");//获取请求参数name
		String[] names = request.getParameterValues("name");//获取请求参数name的值的数组
		Map<String,String[]> ps = request.getParameterMap();//获取参数和值的key-value;
		System.out.println("--------------------遍历参数");
		ps.forEach((a,b)->{
			System.out.println(a+" = " + Arrays.toString(b));
		});
		
		System.out.println("--------------------遍历头信息");
		String headValue = request.getHeader("headerName");//获取请求头
		Enumeration<String> headerNames = request.getHeaderNames();//获取所有的请求头名称
		while(headerNames.hasMoreElements()) {//遍历头信息
			String headerName = headerNames.nextElement();
			System.out.println(headerName+" = "+request.getHeader(headerName));
		}
		
		response.setCharacterEncoding("utf-8");//设置响应的字符集编码
		response.setContentType("text/html;charset=utf-8");//设置文档类型和字符集编码
//		response.getOutputStream();//获取响应[正文]字节输出流
		PrintWriter out = response.getWriter();//获取响应[正文]字符输出流
		
		response.addHeader("headerName", "headerValue");//添加响应头
//		response.sendError(200, "ok");//发送状态码[错误码]和状态消息，200则不需要发送
		
		String uri = request.getRequestURI();//获取请求资源地址
		out.println("<h1>"+uri+"</h1>");
		out.print("<h2>"+LocalDateTime.now().toString()+"</h2>");
		for(int i=1;i<1000;i++) {
			out.println("<h3>送"+name+i+"朵玫瑰</h3>");
		}
		out.flush();
		
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}
